package com.epoch.server.kernel.serve;

import com.epoch.common.Message;
import com.epoch.common.MessageType;
import com.epoch.server.kernel.dao.ChatRecordDao;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 群聊的开启线程
 */
@Slf4j
public class GroupChatConnThread extends Thread {

    public Socket socket;
    public Integer GroupID;

    private final ChatRecordDao chatRecordDao = new ChatRecordDao();
    public GroupChatConnThread(Socket socket, Integer GroupID) {
        this.socket = socket;
        this.GroupID = GroupID;
    }
    @Override
    public void run() {
        boolean first = true;
        String threadName = null;

        while (true){
            try{
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();
                threadName = message.getSenderName();
                //输出服务器端的提示信息
                if (first) {
                    first = false;
                    continue;
                }
                if(message.getMessageType().equals(MessageType.MESSAGE_INFOR_NOR)) {
                    chatRecordDao.addRecord(message);
                    //准备更新每个客户端的界面，遍历更新
                    for (Map.Entry<String, GroupChatConnThread> entry : ClientConnManager.hashMap.entrySet()) {
                        GroupChatConnThread thread = entry.getValue();
                        ObjectOutputStream oos = new ObjectOutputStream(thread.socket.getOutputStream());
                        oos.writeObject(message);
                    }
                } else if (message.getMessageType().equals(MessageType.MESSAGE_INITHIS)){
                    List<String> recordList = chatRecordDao.initChatHistory(message.getGroupId());
                    log.info("收到客户端恢复聊天记录璐请求，已经恢复聊天记录记录{}", recordList.size());
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    Map<String, Object> map = new HashMap<>();
                    map.put("recordList", recordList);
                    Message recordMessage = new Message();
                    recordMessage.setDynamicData(map);
                    oos.writeObject(recordMessage);
                }
            } catch (Exception e){
                log.info(threadName + "用户已退出");
                ClientConnManager.removeClientThread(threadName);
                break;
            }
        }
    }
}
